﻿using AutoMapper;
using ManagementApi.Authorizers;
using ManagementApi.Models;
using ManagementApi.Models.Manage.ProjectSpecialAccount;
using ManagementApi.Mvc.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules.BankSpecialAccount;
using Modules.BankSpecialAccount.Entitys;
using Modules.Constructor;
using Modules.Project;
using Modules.System.User;
using PmSoft.ApplicationContext;
using PmSoft.Entity;
using PmSoft.Utilities;
using static Modules.BankSpecialAccount.BankSpecialAccountConstants;

namespace ManagementApi.Controllers.AdminPannel
{
    /// <summary>
    /// 项目管理员-专户申请接口
    /// </summary>
    [Route("/api/v1/sysuser/projectspecialaccount")]
    [ApiController]
    [Authorize(Roles = "SysUser")]
    public class ProjectSpecialAccountController : ControllerBase
    {
        private readonly BankSpecialAccountService projectSpecialAccountService;
        private readonly BankSpecialAccountPaymentService projectSpecialAccountPaymentService;
        private readonly ProjectService projectService;
        private readonly ConstructorService constructorService;
        private readonly IApplicationContext applicationContext;
        private readonly IMapper mapper;
        private readonly ProjectOwnAuthorizer ownAuthorizer;

        public ProjectSpecialAccountController(BankSpecialAccountService projectSpecialAccountService, IApplicationContext applicationContext, IMapper mapper, BankSpecialAccountPaymentService projectSpecialAccountPaymentService, ProjectOwnAuthorizer ownAuthorizer, ProjectService projectService, ConstructorService constructorService)
        {
            this.projectSpecialAccountService = projectSpecialAccountService;
            this.mapper = mapper;
            this.projectSpecialAccountPaymentService = projectSpecialAccountPaymentService;
            this.applicationContext = applicationContext;
            this.ownAuthorizer = ownAuthorizer;
            this.projectService = projectService;
            this.constructorService = constructorService;
        }

        /// <summary>
        /// author:hzj date:2023/12/21 describe:获取指定专户数据
        /// </summary>
        /// <param name="id">专户id，若ID=0，则只获取单据号</param>
        /// <returns></returns>
        [HttpGet("{id}/form")]
        public ApiResult<ProjectSpecialAccountDto> GetProjectSpecialAccount(int id)
        {
            BankSpecialAccountInfo? data = projectSpecialAccountService.GetProjectSpecialAccount(id);
            if (data == null)
                return ApiResult<ProjectSpecialAccountDto>.Failure("专户不存在");
            return ApiResult<ProjectSpecialAccountDto>.Success(data.AsProjectSpecialAccountDto(applicationContext));
        }

        /// <summary>
        /// author:hzj date:2024/1/13 describe:通过项目Id获取专户信息
        /// </summary>
        /// <param name="projectId">项目Id</param>
        /// <returns></returns>
        [HttpGet("detail/project/{projectId}")]
        public ApiResult<ProjectSpecialAccountDto> GetProjectSpecialAccountByProjectId(int projectId)
        {
            var list = projectSpecialAccountService.GetProjectSpecialAccountByProjectId(projectId).Where(i => i.AccountStatus == 专户状态.正常);
            if (!list.Any())
            {
                return ApiResult<ProjectSpecialAccountDto>.Failure("当前项目不存在专户信息");
            }
            return ApiResult<ProjectSpecialAccountDto>.Success(list.First().AsProjectSpecialAccountDto(applicationContext));
        }

        /// <summary>
        /// author:hzj date:2023/12/21 describe:获取专户列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
        [HttpGet("page")]
        public ApiResult<PageDto<ProjectSpecialAccountDto>> GetProjectSpecialAccounts([FromQuery] BankSpecialAccountQuery query, int pageNum = 1, int pageSize = 20)
        {
            var data = projectSpecialAccountService.GetProjectSpecialAccounts(query, pageNum, pageSize);
            var dtos = data.AsPageDto(source => { return source.AsProjectSpecialAccountDto(applicationContext); });
            return ApiResult<PageDto<ProjectSpecialAccountDto>>.Success(dtos);
        }

        /// <summary>
        /// author:hzj date:2023/12/21 describe:获取收支明细
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
        [HttpGet("page_payment")]
        public ApiResult<PageDto<ProjectSpecialAccountPaymentDto>> GetProjectSpecialAccountPayments([FromQuery] BankSpecialAccountPaymentQuery query, int pageNum = 1, int pageSize = 20)
        {
            var data = projectSpecialAccountPaymentService.GetProjectSpecialAccountPayments(query, pageNum, pageSize);
            var dtos = data.AsPageDto(source => { return source.AsProjectSpecialAccountPaymentDto(applicationContext); });
            return ApiResult<PageDto<ProjectSpecialAccountPaymentDto>>.Success(dtos);
        }

        /// <summary>
        /// author:hzj date:2023/12/21 describe:审核专户
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPut("audit")]
        [PermissionCheck("sys:specialaccount:audit")]
        public ApiResult AuditProjectSpecialAccount(ProjectSpecialAccountAuditForm form)
        {
            #region 仅超管和银行角色可操作

            if (applicationContext.CurrentUser is IDeptUser deptUser && (!deptUser.IsBankAdministrator() && !deptUser.IsSuperAdministrator()))
            {
                return ApiResult.Failure("该账户无此权限");
            }

            #endregion 仅超管和银行角色可操作

            BankSpecialAccountInfo? data = projectSpecialAccountService.GetProjectSpecialAccount(form.Id);
            if (data == null) return ApiResult.Failure("专户信息不存在");
            data.BankNo = form.BankNo;
            data.Username = form.Username ?? string.Empty;
            data.BankMark = data.Username.Contains("专户");
            data.BankType = form.BankType;
            data.BankName = form.BankName;
            data.Balance = 0;
            data.LumpContractorCorpMobile = form.LumpContractorCorpMobile;
            data.LumpContractorCorpChecker = form.LumpContractorCorpChecker;
            data.LumpContractorCorpCardNo = form.LumpContractorCorpCardNo;
            data.ConstructorChecker = form.ConstructorChecker;
            data.ConstructorMobile = form.ConstructorMobile;
            data.ConstructorCardNo = form.ConstructorCardNo;
            data.LastUpdateTime = DateTime.Now;
            //仅手动开户存在以下数据
            data.OptUserName = applicationContext.CurrentUser is IDeptUser user ? user.Name : applicationContext.CurrentUser is SysUser sysuser ? sysuser.Name : string.Empty;
            data.AccountStatus = 专户状态.正常;
            data.AccountCreateTime = DateTime.Now;
            data.OpenDate = DateTime.Now;
            data.ConstructorType = "身份证";
            data.LumpContractorCorpType = "身份证";
            var project = projectService.GetProjectInfo(data.ProjectId);
            if (project != null && string.IsNullOrEmpty(project.BuildPhoneNum))
            {
                project.BuildPhoneNum = data.ConstructorMobile;

                projectService.Update(project);
                var constructor = constructorService.GetConstructorInfo(project.BuildCorpId);
                if (constructor != null)
                {
                    constructor.LinkTel = data.ConstructorMobile;
                    constructorService.Update(constructor);
                }
            }

            projectSpecialAccountService.UpdateProjectSpecialAccount(data);
            return ApiResult.Success("审核成功");
        }

        /// <summary>
        /// 修改审核信息
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPut("updateAuditInfo")]
        [PermissionCheck("sys:specialaccount:update")]
        public ApiResult UpdateAuditInfo(ProjectSpecialAccountAuditForm form)
        {
            #region 仅超管和银行角色可操作

            if (applicationContext.CurrentUser is IDeptUser deptUser && (!deptUser.IsBankAdministrator() && !deptUser.IsSuperAdministrator()))
            {
                return ApiResult.Failure("该账户无此权限");
            }

            #endregion 仅超管和银行角色可操作

            BankSpecialAccountInfo? data = projectSpecialAccountService.GetProjectSpecialAccount(form.Id);
            if (data == null) return ApiResult.Failure("专户信息不存在");
            data.BankNo = form.BankNo;
            data.Username = form.Username ?? string.Empty;
            data.BankMark = data.Username.Contains("专户");
            data.BankType = form.BankType;
            data.BankName = form.BankName;
            data.LumpContractorCorpMobile = form.LumpContractorCorpMobile;
            data.LumpContractorCorpChecker = form.LumpContractorCorpChecker;
            data.LumpContractorCorpCardNo = form.LumpContractorCorpCardNo;
            data.ConstructorChecker = form.ConstructorChecker;
            data.ConstructorMobile = form.ConstructorMobile;
            data.ConstructorCardNo = form.ConstructorCardNo;
            data.LastUpdateTime = DateTime.Now;
            projectSpecialAccountService.UpdateProjectSpecialAccount(data);
            return ApiResult.Success("修改成功");
        }
    }
}